package com.controller;

import com.entity.User;
import com.github.pagehelper.PageInfo;
import com.service.UserService;
import com.vo.QueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.util.List;
import java.util.UUID;

/**
 * @auther: zhangxin
 * @Description:
 */
@Controller
@RequestMapping("/users")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("/list")
    public String list(Model model) {

       model.addAttribute("pageNo",1);
       return "forward:/users/page";
    }

    @RequestMapping("/findById")
    public ModelAndView findById(String id) {
        User user = userService.selectByPrimaryKey(id);
        ModelAndView mav = new ModelAndView();
        mav.addObject("user", user);
        mav.setViewName("/user/edit");
        return mav;
    }

    @RequestMapping("/add")
    public String add() {
        return "/user/add";
    }

    @RequestMapping("/edit")
    public String edit(@Valid User user, Model model) {
        userService.updateByPrimaryKey(user);
        return "redirect:/users/list";

    }

    @RequestMapping("/search")
    public String search(QueryVo queryVo,Model model) {
        List<User> list = userService.search(queryVo);
        model.addAttribute("userList",list);
        return "user/list";

    }

    @RequestMapping("/delete")
    public String delete(QueryVo queryVo,Model model) {
        userService.deleteByIds(queryVo);
        model.addAttribute("pageNo", 1);
        return "redirect:/users/page";

    }


    @RequestMapping("/page")
    public String findByPage(@RequestParam(value = "pageNo", defaultValue = "1") Integer pageNo, Model model) {
        PageInfo<User> pageInfo =  userService.selectByPage(pageNo,2);;
        model.addAttribute("pageInfo", pageInfo);
        return "user/list";

    }

    @RequestMapping("/save")
    public String save(User user, MultipartFile photoFile,HttpServletRequest request) throws IOException {
        //指定上传文件存放的根目录
        String fileRootPath = request.getServletContext().getRealPath("uploads");
        File file = new File(fileRootPath);
        if(!file.exists()){
            // 如果没有文件夹则创建该文件夹
            file.mkdirs();
        }

        //为了避免上传文件重名，可以使用UUID作为文件名
        String uuid = UUID.randomUUID().toString();
        String suffix = photoFile.getOriginalFilename().substring(photoFile.getOriginalFilename().lastIndexOf("."));
        String photoPath = fileRootPath + "\\" + uuid + suffix;

        //保存文件到指定目录
       // String photoPath = fileRootPath + "\\" + photoFile.getOriginalFilename();
        FileCopyUtils.copy(photoFile.getInputStream(), Files.newOutputStream(new File(photoPath).toPath()));
        //MultipartFile的transferTo在保存文件后，会自动删除，所以要自己保存
        //photoFile.transferTo(new File(fileRootPath, photoFile.getOriginalFilename()));


        // 保存商品
        user.setId(UUID.randomUUID().toString().replace("-", ""));
        user.setPhoto(uuid + suffix);
        user.setDepId("1");
        user.setUserName(user.getName());
        user.setStatus(1);
        userService.insert(user);

        return "redirect:/users/page";
    }


    // 文件下载
    @RequestMapping("/download")
    public ResponseEntity<byte[]> download(String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
       User user = userService.selectByPrimaryKey(id);

        //指定上传文件存放的根目录
        String fileRootPath = request.getServletContext().getRealPath("uploads");
        // 获得上传文件的本地路径
        String filePath = fileRootPath + "\\" + user.getPhoto();

        //响应行
        HttpStatus statusCode = HttpStatus.OK;

        //响应头
        HttpHeaders headers=new HttpHeaders();
        headers.add("Content-Disposition","attachment;filename=" + user.getPhoto());

        //响应体
        byte[] body=null;
        InputStream is = new FileInputStream(filePath);
        body=new byte[is.available()];
        is.read(body);

        //使用ResponseEntity实现文件下载
        return new ResponseEntity<byte[]>(body, headers, statusCode);

    }

    @ModelAttribute(value = "user")
    public User getUser(String id) {
        User user = new User();
        if((id != null) && !id.equals("")) {
           user = userService.selectByPrimaryKey(id);
        }
        return user;
    }

}
